package com.treasure.hunt.task

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ScreenUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.lemlin.base.loadCenterImage
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.LuckyFlop
import com.treasure.hunt.mine.MineConfigActivity
import com.treasure.hunt.mode.LuckyViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import kotlinx.android.synthetic.main.activity_task_flop.*
import kotlinx.android.synthetic.main.fragment_hunt_grade.*
import kotlinx.android.synthetic.main.item_task_flop.*


class TaskFlopActivity : ViewModeActivity<LuckyViewMode>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, TaskFlopActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = this, onAnimationEnd = {})
    }

    private val flopAdapter =
        object : BaseQuickAdapter<LuckyFlop, BaseViewHolder>(R.layout.item_task_flop) {

            var selectedPosition = -1
                set(value) {
                    if (field != value) {
                        field = value
                        notifyDataSetChanged()
                    }
                }

            override fun convert(holder: BaseViewHolder, item: LuckyFlop) {

                holder.setText(R.id.tvTaskFlopName, item.title)
                    .setGone(R.id.llTaskFlopPositive, item.id == 0)
                    .setGone(R.id.ivTaskFlopIcon, item.id == 0)
                item.image?.let { image ->
                    val isHttps: Boolean = image.substring(0, 5).contains("http") ||
                            image.substring(0, 5).contains("https")
                    holder.getView<ImageView>(R.id.ivTaskFlopIcon)
                        .loadCenterImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${image}")
                }
                holder.getView<ImageView>(R.id.ivTaskFlopObverse).setImageResource(item.src)

                holder.itemView.layoutParams.height =
                    ((ScreenUtils.getAppScreenWidth() - ConvertUtils.dp2px(12f * 4)) / 3) + ConvertUtils.dp2px(
                        50f
                    )

                holder.itemView.isSelected = holder.layoutPosition == selectedPosition

            }
        }

    private var isOnItemClickListener: Boolean = true

    override val layoutResId: Int
        get() = R.layout.activity_task_flop

    override fun viewModel(): LuckyViewMode {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(
            isLightMode = false,
            bottomColor = R.color.FF_020027,
            view = flTaskFlopBar
        )
    }

    override fun initView() {
        rvTaskFlopBody.apply {
            val decoration = SpacingItemDecoration(
                nSpan = 3,
                vGap = ConvertUtils.dp2px(12f),
                hGap = ConvertUtils.dp2px(12f)
            )
            addItemDecoration(decoration)
        }.adapter = flopAdapter.apply {
            flopAdapter.setNewInstance(getLuckyFlopList())
        }
        flopAdapter.setOnItemClickListener { adapter, view, position ->
            if (isOnItemClickListener)
                flopAdapter.selectedPosition = position
        }

        tvTaskFlopGetNum.setOnClickListener {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 4
            )
            viewModel.videoType(maps)
        }

        tvTaskFlopAway.setOnClickListener {
            val position: Int = flopAdapter.selectedPosition
            if (position == -1) {
                toast("请选择卡片")
            } else if (viewModel.luckyNumLiveData.value?.httpData?.data?.num ?: 0 == 0) {
                toast("翻牌次数不够！")
            } else {
                viewModel.luckyFlop(position)
            }
        }
        tvTaskFlopAgain.setOnClickListener {
            isOnItemClickListener = true
            tvTaskFlopAgain.visibility = View.GONE
            tvTaskFlopAway.visibility = View.VISIBLE
            flopAdapter.selectedPosition = -1
            flopAdapter.setNewInstance(getLuckyFlopList())
        }

        ivTaskFlopBack.setOnClickListener {
            finish()
        }

        tvTaskFlopRule.setOnClickListener {
            MineConfigActivity.open(activity = this, title = "幸运翻牌规则", name = "lucky_video_rule")
        }

    }

    override fun initData() {
        viewModel.luckyGetLuckDraw(type = 4)
    }

    override fun initViewMode() {
        viewModel.luckyNumLiveData.observe(this, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                tvTaskFlopNum.text = "还有 ${it.num} 次翻牌机会"
            }
        })

        viewModel.luckyFlopLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            viewModel.luckyGetLuckDraw(type = 4)
            response.httpData?.data?.let { luckyFlop ->
                flopAdapter.setNewInstance(luckyFlop)
                luckyFlop.find { it.is_select == 1 }?.let {
                    flopPopup.fillData(it).showPopupWindow()
                    viewModel.videoNoReward(advertisementType = 3)
                }
                tvTaskFlopAgain.visibility = View.VISIBLE
                tvTaskFlopAway.visibility = View.GONE
                isOnItemClickListener = false
            }
        })

        viewModel.videoTypeLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {

            }  else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = this, codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = this, codeId = codeId)
            }
        })

        viewModel.videoEndLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                initData()
            }
        })

        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner,
            Observer { isRewardVerify ->
                if (!isRewardVerify)
                    return@Observer
                viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                    viewModel.videoEnd(it.video_log_id)
                }
            })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            }else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = this,codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = this,codeId = codeId)
            }
        })

        viewModel.viewAdLiveData.observe(this, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })
    }

    private fun getLuckyFlopList(): MutableList<LuckyFlop> {
        val flops: MutableList<LuckyFlop> = mutableListOf()
        for (index: Int in 0..5) {
            flops.add(LuckyFlop(id = 0).apply { src = R.mipmap.ic_20707 })
        }
        return flops
    }
}